#include "cache_handle.h"

QueueHandle_t cache_queue_handle;
static TaskHandle_t cache_handle;

/*
static void print_data_hex(uint8_t *data, u16 len)
{   
    printf("------> data: cache");
    for (int i = 0; i < len; i++) 
    {
        printf(" 0x%x", data[i]);
    }
    
    printf(", len1: %d\n", len);
}
*/


u16 cache_read(u8 *g_uart_buf)
{
  cache_param *buffer = NULL;
  uint16_t received=0;
  if(xQueueReceive(cache_queue_handle,&buffer,portMAX_DELAY))
  {
    if (buffer != NULL)
     {
        memcpy(g_uart_buf,buffer->data,buffer->len);
        received = buffer->len;
        //print_data_hex(g_uart_buf,buffer->len);
        vPortFree(buffer->data);
        vPortFree(buffer);
        return received;
     }
     else
     {
        return 0;
     }
  }
  else
  {
    return 0;
  }  
}



void cache_task()
{
    u8 g_uart_buf[BUF_SIZE1];
    LOG_INFO("disp_task : enter cache_task()\n");
    cache_queue_handle = xQueueCreate(20,sizeof(cache_param *));
    static uint16_t total_received=0;
    
    while (1)
    {
      uint16_t received=0;
      if ((received = cache_read(g_uart_buf+total_received)) !=0)
      {
        //printf("received1 size %d:\n", received);
        if((g_uart_buf[total_received+received-1] == END_MARKER) && (g_uart_buf[total_received+received-2] == END_MARKER ) && (g_uart_buf[total_received+received-3] == END_MARKER)) //利用包尾帧判断一个帧是否接收完毕
        {
            // 数据包结束，处理数据
            parse_cloud_data(g_uart_buf,total_received+received-3);
        }

        // 更新总接收字节数
        total_received += received;
        // 如果收到了结束标记，重置接收计数器
        if ((g_uart_buf[total_received-1] == END_MARKER)) 
        {
          total_received = 0;
          memset(g_uart_buf,0,BUF_SIZE1); 
        }
      }
      else
      {
        LOG_INFO("size is zero, ignore...\n");
      }
    }
}




void cache_init(void)
{
    printf("cache_init():enter\n");
    xTaskCreate(cache_task, "cache_task", 4096, NULL, TASK_PROP_DISPLAY, &cache_handle);
}
